﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json.Linq;

namespace Yakool.Order
{
    class CrawlTask : ITask
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private SpiderContext context;

        public CrawlTask(SpiderContext ctx)
        {
            context = ctx;
        }

        public void RunSynchronously()
        {
            var orderUrl = context.Settings["orderUrl"].ToString();

            orderUrl = string.Format(orderUrl, new Random().NextDouble());

            var rs = HttpBot.Get(orderUrl, null, context.Cookie);
            if (rs.Status != 200)
                throw new ApplicationException("Fetch order list failed");

            context.Order = JObject.Parse(rs.Body);

            var orderFile = Path.Combine(context.IntermediateDir, "order.json");
            File.WriteAllText(orderFile, context.Order.ToString());
            log.InfoFormat("Order list retrieved");
        }
    }
}
